/*
* @Author: Administrator
* @Date:   2016-11-22 15:52:28
* @Last Modified by:   Administrator
* @Last Modified time: 2016-11-23 09:43:08
*/

'use strict';

var express = require('express');
    var fs = require('fs');

    var marked = require('marked');
var pygmentize = require('pygmentize-bundled');
    var app = express();
marked.setOptions({
  highlight: function (code, lang, callback) {
    pygmentize({ lang: lang, format: 'html' }, code, function (err, result) {
      callback(err, result.toString());
    });
  }
});

//自定义方法，接收md文件内容，返回一个包含转换结果的回调函数
function markdown2html(data, callback) {
  marked(data, function (err, content) {
    return callback(err, content);
  });
}
/*function getBlogList(blogDir) {
  fs.readdir(blogDir, function (err, files) {
    var blogList = [];
    var blogItem={};
    if (files && files.length) {
        files.forEach(function (filename) {
          //split file name and generate url...
          //...
          //create a blogItem { title: blogTitle, url: blogUrl }
          blogItem.title = filename;
          blogItem.url = '/blog/2014/04/01/'+filename;
          blogList.push(blogItem);
          console.log(blogList);
        });
    }
    return blogList;
  });
}*/
function getBlogList(blogDir,callback){
  fs.readdir(blogDir,function(err,files){
    var blogList = [];

    function add(title){
      this.title=title;
      this.url = 'blog/'+title;
    }
    var a;
    var arr=[];
    var arr1=[];
    (function iterator(i){
      if(i == files.length){

        callback(blogList);
        return
      }
      fs.stat("./blogs/" + files[i],function(err,stats){
        //检测成功之后做的事情
        if(!stats.isDirectory()){
          //如果是文件夹，那么放入数组。不是，什么也不做。
/*blogItem.title = files[i];
blogItem.url = 'blog/'+files[i];
          blogList.push(blogItem);*/

          arr = files[i].slice(0,-3).split('');
          for (var j = 0; j < arr.length; j++) {
              if('-'!=arr[j]){
                arr1.push(arr[j])
              }
          }
          a = arr1.join('/');

          blogList.push(new add(a));
        }
        iterator(i+1);
      });
    })(0)
  })
}

app.get('/', function (req, res) {
  var html = '';
  getBlogList('./blogs',function(blogList){
    if (blogList && blogList.length) {
    blogList.forEach(function (blog) {
      html += '<a href="'+ blog.url +'">' + blog.title + '</a><br/>';
    });
    res.send(html);
  } else {
    res.send('No Blogs Found.');
  }
  });

});

app.get('/blog/:year/:month/:day/:title', function (req, res) {
  var fileName =
    './blogs/' +
    req.params.year + '-' +
    req.params.month + '-' +
    req.params.day + '-' +
    req.params.title + '.md';
  fs.readFile(fileName, 'utf-8', function (err, data) {
  if (err) res.send(err);

  console.log(data);
  console.log(typeof(data));
  markdown2html(data, function (err, content) {
    if (err) res.send(err);
    res.send(content);
  });
});
});

    app.listen(3000);